package edu.uwp.cs.android.sco;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import edu.uwp.cs.android.sco.entities.DaoMaster;
import edu.uwp.cs.android.sco.entities.DaoMaster.DevOpenHelper;
import edu.uwp.cs.android.sco.entities.DaoSession;
import edu.uwp.cs.android.sco.entities.Disability;
import edu.uwp.cs.android.sco.entities.Student;
import edu.uwp.cs.android.sco.entities.StudentDao;

/**
 * This prototype was developed for the Mobile Device Programming class
 * in the Spring Semester 2012 at the University of Wisconsin Parkside.
 * 
 * @author Michael Tiede, Matthias Kleinert, Moritz Duettmann
 * @since May 2012
 */
public class ConvertToPDFActivity extends Activity {
	
	// database management
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private StudentDao studentDao;
    
    // buttons
    private Button sendMailButton;
    private Button openPdfButton;
    private Button doneButton;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.convert_to_pdf);
        
        sendMailButton = (Button) findViewById(R.id.convert_to_pdf_sendMail);
        openPdfButton = (Button) findViewById(R.id.convert_to_pdf_openPdf);
        doneButton = (Button) findViewById(R.id.convert_to_pdf_done);

        DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "sco-v1.db", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        studentDao = daoSession.getStudentDao();
        
        long studentId = getIntent().getLongExtra("studentId", -1l);
        
        if(studentId == -1l){
           Log.e("ConvertToPDFActivity", "ERROR: Could not catch studentId from intent!");
           finish();
        }
        
        // load student and create PDF document
	    Student student = studentDao.load(studentId);
        createPDF(student);
        
        sendMailButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMail();
            }
        });
        
        openPdfButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               openPDF();
            }
        });
        
        doneButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    

    private void createPDF(Student student) {
    	// Font definitions
    	Font fontHeader1 = new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD);
    	Font fontHeader2 = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    	Font fontHeader3 = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
    	Font fontDefault = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
    	Font fontBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    	Font fontImportant = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
    	
        try {
        	// Initialize and open document
            Document document = new Document();
            FileOutputStream fOut = openFileOutput("export.pdf", Context.MODE_WORLD_READABLE);
            PdfWriter.getInstance(document, fOut);
            document.open();

            // Adding meta-data
            document.addTitle("Student: " + student.getFName() + " " + student.getLName());
            document.addSubject("The student might have disabilities.");
    		document.addAuthor("Generated by Student Class Observer");
    		document.addCreator("Generated by Student Class Observer");

    		// Headline
    		Paragraph paragraph = new Paragraph("Student Documentation", fontHeader1);
    		addEmptyLine(paragraph, 1);
    		document.add(paragraph);
    		
    		// Subtitle
    		paragraph = new Paragraph("This data is strictly confidential!", fontHeader2);
    		addEmptyLine(paragraph, 2);
    		document.add(paragraph);
    		
    		// Intro including student name
    		String intro = "I recognized that my student " +  student.getFName() + " " + student.getLName() + " has problems in different categories (see below). \nThis documentation contains an overview over the recognized behaviors of my student. \nIt was generated by the Student Class Observer Application which I use during my lecture. \nI have the permission of my student " + student.getFName() + " " + student.getLName() + " to sent this data to you.";
    		paragraph = new Paragraph(intro , fontBold);
    		addEmptyLine(paragraph, 2);
    		document.add(paragraph);
    		
    		// student name
    		paragraph = new Paragraph("Student Name: " +  student.getFName() + " " + student.getLName(), fontHeader2);
    		addEmptyLine(paragraph, 1);
    		document.add(paragraph);
    		
    		// include disability list
    		for (Disability dis : student.getDisabilities()) {
				// Headline category
	    		paragraph = new Paragraph("Category: " + dis.getCategory() + "", fontHeader3);
	    		addEmptyLine(paragraph, 1);
	    		document.add(paragraph);
				
				// Headline disability name and category
	    		paragraph = new Paragraph(dis.getName(), fontBold);
	    		addEmptyLine(paragraph, 1);
	    		document.add(paragraph);
	    		
	    		// Rating for disability
	    		paragraph = new Paragraph("Rating: " + dis.getRating() + " out of 5", fontBold);
	    		
	    		addEmptyLine(paragraph, 1);
	    		document.add(paragraph);
	    		
	    		// Info about this disability
	    		paragraph = new Paragraph("Info: " + dis.getInfo(), fontDefault);
	    		addEmptyLine(paragraph, 2);
	    		document.add(paragraph);
			}
    		
    		// Add note block
    		addEmptyLine(paragraph, 2);
    		paragraph = new Paragraph("Notes / Comments:", fontHeader2);
    		addEmptyLine(paragraph, 1);
    		document.add(paragraph);
    		
    		paragraph = new Paragraph(student.getNote() , fontDefault);
    		addEmptyLine(paragraph, 2);
    		document.add(paragraph);

    		// close document and streams
            document.close();
            fOut.flush();
            fOut.close();

            System.out.println("Finished createPDF() method...");
            Toast.makeText(this, "PDF File created", Toast.LENGTH_LONG).show();
        }
        catch (FileNotFoundException e) {
            System.out.println("FILE NOT FOUND EXCEPTION");
            e.printStackTrace();
        }
        catch (DocumentException e) {
            System.out.println("DOCUMENT EXCEPTION");
            e.printStackTrace();
        }
        catch (IOException e) {
            System.out.println("IO EXCEPTION");
            e.printStackTrace();
        }
    }

    private void openPDF() {
        String[] list = fileList();
        for (int i = 0; i < list.length; i++) {
            System.out.println(list[i]);
        }

        System.out.println("FILES DIR: " + getFilesDir());

        File file = new File(getFilesDir() + "/" + "export.pdf");

        if (file.exists()) {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            try {
                startActivity(intent);
                System.out.println("INTENT GESTARTET !!!");
            }
            catch (ActivityNotFoundException e) {
                Toast.makeText(ConvertToPDFActivity.this, "Error: No application available to view the PDF file.", Toast.LENGTH_LONG).show();
                System.out.println("NO APPLICATION AVAILABLE !!!");
            }
        }
        else {
            System.out.println("ERROR OPEN PDF FILE !!!");
        }
    }
    
    private void addEmptyLine(Paragraph paragraph, int number) {
		for (int i = 0; i < number; i++) {
			paragraph.add(new Paragraph(" "));
		}
	}

    /**
     * Sends the pdf file as a mail.
     */
    private void sendMail() {
        final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("application/pdf");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "");

        String root = Environment.getExternalStorageDirectory().toString();
        
        // Attention now follows the darkest vodoo out of the hell
        Uri pdfUri = Uri.fromFile(new File(root + "/../.." + getFilesDir() + "/"+ "export.pdf"));

        emailIntent.putExtra(Intent.EXTRA_STREAM, pdfUri); 
        startActivity(Intent.createChooser(emailIntent, "Choose you mail client..."));
    }
}
